package com.shop.cart.listen;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.shop.cart.controller.CartController;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * @author ghy
 * @version 1.0
 * @date 2020-11-05
 */
@Component
public class CartListener {

    @Autowired
    CartController cartController;


    @RabbitListener(queues = "cartQueue")
    public void consume(Message message, Channel channel) throws Exception {

        byte[] body = message.getBody();
        String msg = new String(body,"UTF-8");
        Map<String,Object> map = JSON.parseObject(msg, Map.class);

        String cart_token = (String) map.get("cart_token");
        String login_token = (String)map.get("login_token");
        //HttpServletResponse resp = (HttpServletResponse)map.get("resp");

        cartController.merge(cart_token, login_token);

        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        channel.basicAck(deliveryTag, false);
    }

}
